/**
 * @Description: 存储设置
 * @author randy
 * @date 2019/11/28 下午17:21
 */
import {
  Alert,
  Button,
  Form,
  Input,
  Icon,
  Select,
  message,
  Col,
  Row,
  Divider,
  Typography,
  InputNumber,
  Spin, List,
} from 'antd';
import Modal from 'drag-modal';
// eslint-disable-next-line import/no-extraneous-dependencies
import {FormattedMessage, formatMessage} from 'umi-plugin-react/locale';
import React, {Component, Fragment} from 'react';
import {connect} from 'dva';
import uiUtils, {rulesReg} from '../../../utils/uiUtils';
import {getWebPath} from '../../../utils/request';
import {requestLists, requestPromise} from '@/utils/request';

const FormItem = Form.Item;
const {Option} = Select; // 头像组件 方便以后独立，增加裁剪之类的功能
const {Text, Title} = Typography;
let id = 1;

@connect(({accountAndsettings}) => ({
  // currentUser: accountAndsettings.currentUser,
  currentUser: '',
}))
class StorageSetting extends Component {
  view = undefined;

  constructor(props) {
    super(props);
    id = 1;
    this.state = {
      data: {},
      testConfigLoading: false,
    };
  }

  componentDidMount() {
    this.setState({loading: true});
    this.getMailInfo();
    this.getSpaceInfo();
  }

  getMailInfo = () => {
    const {form} = this.props;
    form.setFieldsValue({
      keys: [],
      emails: [],
    });
    requestPromise(`${getWebPath('sys/config/storage/info')}`, {
      method: 'GET',
    }).then(res => {
      if (res.code === 0) {
        const data = res.data.vo;
        if (data.clearTime !== undefined && data.clearTime.indexOf(':') !== -1) {
          data.clearTimeHour = data.clearTime.split(':')[0];
          data.clearTimeMin = data.clearTime.split(':')[1];
        }
        if (data.emails !== undefined) {
          for (let i = 0; i < data.emails.length; i += 1) {
            if (i > 0) {
              this.add();
            }
          }
          form.setFieldsValue({
            emails: data.emails,
          });
        }
        this.setState({
          data,
          path: res.data.path,
          systemDiskInfo: res.data ? res.data.systemDiskInfo : [],
        });
      }
    });
  };

  getSpaceInfo = () => {
    requestPromise(`${getWebPath('sys/config/storage/getSpace')}`, {
      method: 'GET',
    }).then(res => {
      if (res.code === 0) {
        this.setState({
          spaceInfo: res.data,
          loading: false,
        });
      }
    });
  };

  handleOk = e => {
    this.setState({loading: true});
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const info = this.props.form.getFieldsValue();
        info.clearTime = `${info.clearTimeHour}:${info.clearTimeMin}`;
        requestPromise(`${getWebPath('sys/config//storage/save')}`, {
          method: 'POST',
          body: info,
        }).then(res => {
          this.setState({
            loading: false,
          });
          if (res.code === 0) {
            message.success('保存成功');
          }
        });
      }
    });
  };

  clearLog = e => {
    this.setState({loading: true});
    requestPromise(`${getWebPath('sys/config/storage/clearLog')}`, {
      method: 'GET',
    }).then(res => {
      if (res.code === 0) {
        this.setState({
          visible: true,
          num: res.num,
          loading: false,
        });
      }
    });
  };

  onChange = e => {
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  add = () => {
    const {form} = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // eslint-disable-next-line no-plusplus
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  };

  remove = k => {
    const {form} = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 0) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  testConfig = () => {
    this.setState({testConfigLoading: true});
    requestPromise(`${getWebPath('sys/config/storage/checkSysDiskTest')}`, {
      method: 'GET',
    }).then(res => {
      if (res.code === 0) {
        this.setState({
          testConfigLoading: false,
        });
        uiUtils.showMessage("测试成功，请检查邮箱邮件！", "success");
      }
    });
  };

  render() {
    const ItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 3},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 21},
      }, //5+19=24,少一个栅格
    };
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      }, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 24, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 24}; //col之间的间隔?px
    const {
      form: {getFieldDecorator},
      form,
    } = this.props;
    const model = this.state.data;

    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 6, offset: 2},
      },
    };

    getFieldDecorator('keys', {initialValue: []});
    const keys = form.getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <Form.Item {...ItemLayout} label="" required={false} key={k}>
        {getFieldDecorator(`emails[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [
            {
              required: false,
              message: '请输入邮箱地址',
            },
            rulesReg('email'),
          ],
        })(<Input style={{width: '40%'}} placeholder="请输入邮箱地址"/>)}&nbsp;&nbsp;
        {keys.length > 0 ? (
          <Icon
            className="dynamic-delete-button"
            type="minus-circle-o"
            onClick={() => this.remove(k)}
          />
        ) : null}
      </Form.Item>
    ));

    const hours = [];
    for (let i = 0; i < 24; i += 1) {
      if (i.toString().length === 1) {
        hours.push(<option key={i}>0{i}</option>);
      } else {
        hours.push(<option key={i}>{i}</option>);
      }
    }
    const mins = [];
    for (let i = 0; i < 60; i += 1) {
      if (i.toString().length === 1) {
        mins.push(<option key={i}>0{i}</option>);
      } else {
        mins.push(<option key={i}>{i}</option>);
      }
    }

    const text = (
      <div>
        <p>
          <Text strong>会话录像存储路径： {this.state.path}</Text>
        </p>
        {this.state.spaceInfo !== undefined ? (
          <p>
            <Text strong>
              会话录像存储空间：
              {this.state.spaceInfo !== undefined ? this.state.spaceInfo.space : ''}
            </Text>
          </p>
        ) : (
          ''
        )}
      </div>
    );

    const diskInfo = this.state.systemDiskInfo ? this.state.systemDiskInfo : [];
    const diskInfoEle = diskInfo.map((value, index) => (
      <div>
        <span style={{marginRight: 20}}>{`磁盘：${value.mount}`}</span>
        <span style={{marginRight: 20}}>{`总大小：${value.totalSpace}`}</span>
        <span style={{marginRight: 20}}>{`剩余：${value.freeSpace}（占比${value.freeSpaceProportion}%）`}</span>
      </div>)
    );

    return (
      <div layout="vertical" hideRequiredMark>
        <Spin spinning={this.state.loading}>
          <Modal
            title="清理系统日志"
            visible={this.state.visible}
            // onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
              <Button key="close" onClick={this.handleCancel}>
                关闭
              </Button>,
            ]}
          >
            <p>
              已清除系统日志 <Text strong>{this.state.num}</Text> 条
            </p>
          </Modal>
          <Col {...colSpanLayout}>
            <Alert message={text} type="info"/>
          </Col>
          <Divider dashed/>
          <Col {...colSpanLayout}>
            <Title level={4}>系统日志</Title>
            <FormItem label="保留时间:" {...ItemLayout}>
              {getFieldDecorator('logTimeout', {
                initialValue: model.logTimeout !== undefined ? model.logTimeout : 0,
                rules: [
                  {
                    required: true,
                    message: '保留时间不能为空',
                  },
                ],
              })(<InputNumber min={0} max={365}/>)}
              &nbsp;天 &nbsp;&nbsp;
              <Text type="secondary">
                30~365。仅保留指定天数的系统日志，为0则永久保留，默认为0。
              </Text>
            </FormItem>
          </Col>
          <Divider dashed/>
          <Col {...colSpanLayout}>
            <Title level={4}>会话录像</Title>
            <FormItem label="保留时间:" {...ItemLayout}>
              {getFieldDecorator('sessionTimeout', {
                initialValue: model.sessionTimeout !== undefined ? model.sessionTimeout : 0,
                rules: [
                  {
                    required: true,
                    message: '保留时间不能为空',
                  },
                ],
              })(<InputNumber min={0} max={365}/>)}
              &nbsp;天 &nbsp;&nbsp;
              <Text type="secondary">
                30~365。仅保留指定天数的会话录像（以会话开始时间为准），为0则永久保留。默认为0。
              </Text>
            </FormItem>
          </Col>
          <Divider dashed/>
          <Col {...colSpanLayout}>
            <Title level={4}>自动清理</Title>
            <FormItem label="时间点:" {...ItemLayout}>
              {getFieldDecorator('clearTimeHour', {
                initialValue: model.clearTimeHour === undefined ? '00' : model.clearTimeHour,
              })(<Select style={{width: 85}}>{hours}</Select>)}
              &nbsp;时&nbsp;
              {getFieldDecorator('clearTimeMin', {
                initialValue: model.clearTimeMin === undefined ? '00' : model.clearTimeMin,
              })(<Select style={{width: 85}}>{mins}</Select>)}
              &nbsp;分 &nbsp;&nbsp;
              <Text type="secondary">每天在指定时间点清理超出保留时间的数据。</Text>
            </FormItem>
            <Button
              type="primary"
              icon="delete"
              style={{
                marginLeft: 20,
                marginBottom: 20,
                backgroundColor: '#61B660',
                borderColor: '#61B660',
              }}
              onClick={this.clearLog}
            >
              <FormattedMessage id="storagesettings.basic.save" defaultMessage="立即清理"/>
            </Button>
          </Col>
          <Divider dashed/>
          <Col {...colSpanLayout}>
            <Title level={4}>磁盘预警</Title>
            <Alert message={<Fragment>{diskInfoEle}</Fragment>} type="info"/>
            <FormItem label="磁盘空间低于:" {...ItemLayout}>
              {getFieldDecorator('diskSizeLimit', {
                initialValue: model.diskSizeLimit !== undefined ? model.diskSizeLimit : 0,
                rules: [
                  {
                    required: false,
                    message: '请输入值',
                  },
                ],
              })(<InputNumber min={0} max={999999}/>)}
              &nbsp;GB时进行邮件通知。
            </FormItem>
            <span>通知邮箱：</span>
            <Form.Item {...ItemLayout} label="" required={false} key={0}>
              {getFieldDecorator(`emails[0]`, {
                validateTrigger: ['onBlur'],
                rules: [
                  {
                    required: false,
                    message: '请输入邮箱地址',
                  },
                  rulesReg('email'),
                ],
              })(<Input style={{width: '40%'}} placeholder="请输入邮箱地址"/>)}
            </Form.Item>
            {formItems}
            <Form.Item {...ItemLayout}>
              <Button type="dashed" onClick={this.add} style={{width: '40%'}}>
                <Icon type="plus"/> 添 加 邮 箱
              </Button>
            </Form.Item>
          </Col>
          <Col {...colSpanLayout}>
            <Form.Item {...ItemLayout}>
              <Button
                style={{marginBottom: 5}}
                size="small"
                loading={this.state.testConfigLoading}
                onClick={this.testConfig}>试一下
              </Button>
            </Form.Item>
          </Col>
          <Divider dashed/>
          <Row gutter={{...rowGutterPxLayout}}>
            <Col {...colSpanLayout}>
              <Button type="primary" style={{marginTop: 20}} onClick={this.handleOk}>
                <FormattedMessage id="storagesettings.basic.save" defaultMessage="保存存储设置"/>
              </Button>
            </Col>
          </Row>
        </Spin>
      </div>
    );
  }
}

export default Form.create()(StorageSetting);
